import axios from 'axios';
import * as codes from './returnCode';


let util = {};
util.ajax = {};

const siteDomain = 'http://'+window.location.hostname+'/';
util.vars = {
  ajaxUrl: siteDomain+'api/',
  htmlUrl: siteDomain
};

axios.interceptors.response.use(function (response) {

  // 数据请求成功

  if (response.data.code === codes.SUCCESS_CODE) {


    return response.data;

  } else if (response.data.code === codes.USER_NOT_LOGIN_CODE) {
    // 未登录

    setTimeout(() => {
      window.location.href = util.vars.htmlUrl + 'index.html';
    }, 100);

    return response.data;

  } else if (response.data.code === codes.USER_INFO_NULL_CODE) {
    // 未完善信息

    setTimeout(() => {
      /* window.location.href = 'http://saas.davfang.com/html/index.html/LoginRegister';*/
      window.location.href = util.vars.htmlUrl + 'index.html#/LoginRegister';
    }, 100);
    return response.data;

  } else {

    return response.data;
  }

}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);

});

axios.defaults.timeout = 30000;

util.ajax.get = function (url, baseURL) {


  return new Promise((resolve, reject) => {

    axios({
      method: 'get',
      url,
      baseURL: baseURL||util.vars.ajaxUrl,
      withCredentials: true
    }).then(res => {
      resolve(res)
    })
  });

};
util.ajax.post = function (url, params, config) {

  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url,
      /* data: util.jsonStringify(params),*/
      data: params,
      config,
      baseURL: util.vars.ajaxUrl,
      withCredentials: true

    }).then(res => {
      resolve(res)
    })
  });


};


util.ajax.postUpload = function (url, params, callback) {

  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url,
      data: params,
      onUploadProgress: function (progressEvent) { //原生获取上传进度的事件
        if (progressEvent.lengthComputable) {
          //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
          //如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
          callback(progressEvent);
        }
      },
      baseURL: util.vars.ajaxUrl,
      withCredentials: true

    }).then(res => {
      resolve(res)
    })
  });


};


util.GetParameterUrl = function (name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let urlLink = window.location.href;
  let hrefLink = urlLink.indexOf('?') > -1 ? urlLink.indexOf('#') > -1 ? urlLink.split('?')[1].split('#')[0] : urlLink.split('?')[1] : '';
  let r = hrefLink.match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};

util.formatTime = function (timestamp) {

  let nowD = new Date();
  let time = new Date(timestamp);
  let o = {
    "YY": time.getFullYear(),//年份
    "MM": time.getMonth() + 1, //月份
    "dd": time.getDate(), //日
    "hh": time.getHours() % 12 == 0 ? 12 : time.getHours() % 12, //小时
    "HH": time.getHours(), //小时
    "mm": time.getMinutes(), //分
  };
  let nowO = {
    "YY": nowD.getFullYear(),//年份
    "MM": nowD.getMonth() + 1, //月份
    "dd": nowD.getDate(), //日
    "hh": nowD.getHours() % 12 == 0 ? 12 : nowD.getHours() % 12, //小时
    "HH": nowD.getHours(), //小时
    "mm": nowD.getMinutes(), //分
  };
  if (o.YY == nowO.YY && o.MM == nowO.MM && o.dd == nowO.dd && o.HH == nowO.HH) {
    if ((parseInt(nowO.mm) - parseInt(o.mm)) < 10) {
      return '刚刚';
    } else {
      return `${o.YY}-${('0' + o.MM).slice(-2)}-${('0' + o.dd).slice(-2)} ${('0' + o.HH).slice(-2)}:${('0' + o.mm).slice(-2)}`;
    }
  }
  else {
    return `${o.YY}-${('0' + o.MM).slice(-2)}-${('0' + o.dd).slice(-2)} ${('0' + o.HH).slice(-2)}:${('0' + o.mm).slice(-2)}`;
  }
};


util.formatDate = function (date) {

  let dateFor = date.replace(/\-/g, "/");

  let time = new Date(dateFor);
  let nowD = new Date();
  let o = {
    "YY": time.getFullYear(),//年份
    "MM": time.getMonth() + 1, //月份
    "dd": time.getDate(), //日
    "hh": time.getHours() % 12 == 0 ? 12 : time.getHours() % 12, //小时
    "HH": time.getHours(), //小时
    "mm": time.getMinutes(), //分
  };
  let nowO = {
    "YY": nowD.getFullYear(),//年份
    "MM": nowD.getMonth() + 1, //月份
    "dd": nowD.getDate(), //日
    "hh": nowD.getHours() % 12 == 0 ? 12 : nowD.getHours() % 12, //小时
    "HH": nowD.getHours(), //小时
    "mm": nowD.getMinutes(), //分
  };


  if (o.YY == nowO.YY) {

    if (o.MM == nowO.MM) {

      let hTotal = (nowO.dd - o.dd) * 24 + Math.abs(nowO.HH - o.HH);




      if (hTotal > 72 && hTotal < 96) {

        return '三天前';

      } else if (hTotal < 72 && hTotal > 48) {

        return '两天前';

      } else if (hTotal > 24 && hTotal < 48) {

        return '昨天';

      } else if (hTotal < 24 && hTotal > 3) {

        return '今天';

      } else if (hTotal <= 3 && hTotal > 2) {

        return '2小时前';

      } else if (hTotal <= 2 && hTotal > 1) {

        return '1小时前';

      } else if (hTotal == 0 && (parseInt(nowO.mm) - parseInt(o.mm)) > 10) {

        return (parseInt(nowO.mm) - parseInt(o.mm)) + '分钟前'

      } else if ((parseInt(nowO.mm) - parseInt(o.mm)) < 10) {

        return '刚刚';

      } else {

        return `${o.YY}-${('0' + o.MM).slice(-2)}-${('0' + o.dd).slice(-2) }`;

      }


    } else {

      return `${o.YY}-${('0' + o.MM).slice(-2)}-${('0' + o.dd).slice(-2) }`;


    }

  } else {

    return `${o.YY}-${('0' + o.MM).slice(-2)}-${('0' + o.dd).slice(-2) }`;

  }


};
util.jsonStringify = function (arg) {
  let qsArr = [];
  for (let k in arg) {
    let v = arg[k];
    qsArr.push({
      name: k,
      value: ("" + v).toString()
    })
  }
  for (let i = 0; i < qsArr.length; i++) {
    qsArr[i] = [qsArr[i].name, qsArr[i].value].join('=')
  }
  return qsArr.join('&');
};

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
  var dataURL = canvas.toDataURL("image/" + ext);
  return dataURL;
}

util.getBase64 = function (imgUrl) {
  var image = new Image();
  image.crossOrigin = '';
  image.src = imgUrl;
  image.onload = function () {
    var base64 = getBase64Image(image);
    // console.log(base64)
  }

}
export default util;


